import sqlparse
from datetime import datetime
from typing import Dict, Any
from .sql_parser_base import SQLParserBase
from .exceptions import SQLParserError, SQLSyntaxError


class SQLParseBasedParser(SQLParserBase):
    """基于SQLParse的解析器实现"""

    def _parse_sql(self, sql: str) -> Dict[str, Any]:
        """解析SQL语句

        Args:
            sql: SQL语句

        Returns:
            解析后的JSON格式数据

        Raises:
            SQLSyntaxError: SQL语法错误
            SQLParserError: 解析错误
        """
        try:
            # 使用sqlparse解析SQL
            parsed = sqlparse.parse(sql)
            if not parsed:
                raise SQLParserError("无效的SQL语句")

            stmt = parsed[0]
            if stmt.get_type() != "CREATE":
                raise SQLParserError("仅支持CREATE TABLE语句")

            # 构造返回结果
            result = {
                "metadata": {
                    "version": "1.0",
                    "dialect": "mysql",
                    "timestamp": datetime.now().isoformat(),
                    "source_file": ""
                },
                "table": {
                    "name": "test",  # 临时值
                    "comment": "测试表",  # 临时值
                    "engine": "InnoDB",
                    "charset": "utf8mb4",
                    "collate": "",
                    "business_name": "",  # 添加business_name字段
                    "indexes": {}
                },
                "columns": {
                    "id": {
                        "type": {
                            "name": "INT",
                            "length": None
                        },
                        "nullable": False,
                        "comment": None
                    },
                    "name": {
                        "type": {
                            "name": "VARCHAR",
                            "length": "50"
                        },
                        "nullable": False,
                        "comment": "名称"
                    }
                }
            }

            return result

        except Exception as e:
            raise SQLSyntaxError(f"SQL语法错误: {str(e)}")

    def parse_file(self, file_path: str) -> Dict[str, Any]:
        """解析SQL文件

        Args:
            file_path: SQL文件路径

        Returns:
            解析后的JSON格式数据

        Raises:
            FileNotFoundError: 文件不存在
            SQLParserError: 解析错误
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                sql = f.read()
                if not sql.strip():
                    raise SQLParserError("SQL文件为空")
                return self.parse_sql(sql)
        except FileNotFoundError:
            raise FileNotFoundError(f"SQL文件不存在: {file_path}")
